package com.v1.video.adapter;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.activity.OtherPersonHomeActivity;
import com.v1.video.activity.PaikeVideoDetailActivity2;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.ScenarioVideoInfo;
import com.v1.video.domain.UploadInfo;
import com.v1.video.domain.VideoInfo;
import com.v1.video.interfaces.OnVideoSpecialMenu;
import com.v1.video.util.Logger;
import com.v1.video.util.Utility;
import com.v1.video.util.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author wangfang
 * 
 */
public class GridWaterfallAdapter extends BaseAdapter {

	private final String TAG = "TAG";
	private Context mContext;
	private LayoutInflater mLayoutInflater;
	private List<VideoInfo> mLstData;
	private int mHeight;
	private boolean mIsFreq = false;
	private boolean isMySelf = true;
	private float margin;
	private float marginleft;
	private float marginbottom;
	private OnVideoSpecialMenu mOnVideoSpecialMenu;

	public GridWaterfallAdapter(Context context) {
		this.mContext = context;
		mLayoutInflater = LayoutInflater.from(mContext);
		mLstData = new ArrayList<VideoInfo>();
		margin = this.mContext.getResources().getDimension(
				R.dimen.list_item_margin);
		marginleft = this.mContext.getResources().getDimension(
				R.dimen.grid_item_second_titile_left_margin);
		marginbottom = this.mContext.getResources().getDimension(
				R.dimen.grid_item_second_titile_bottom_margin);
		mHeight = Utils.computeImageHeight(context, (int) margin * 3);
	}

	public List<VideoInfo> getmLstData() {
		return mLstData;
	}

	public void setmLstData(List<VideoInfo> mLstData) {
		if(mLstData!=null){
			this.mLstData.addAll(mLstData);
		}
		this.notifyDataSetChanged();
	}

	public void updata(List<VideoInfo> mLstData, boolean refresh) {
		if (refresh) {
			this.mLstData.clear();
		}
		if (mLstData != null) {
			this.mLstData.addAll(mLstData);
		}
		this.notifyDataSetChanged();
	}

	public void setmIsFreq(boolean mIsFreq) {
		this.mIsFreq = mIsFreq;
	}

	public boolean isMySelf() {
		return isMySelf;
	}

	public void setMySelf(boolean isMySelf) {
		this.isMySelf = isMySelf;
	}

	public OnVideoSpecialMenu getmOnVideoSpecialMenu() {
		return mOnVideoSpecialMenu;
	}

	public void setmOnVideoSpecialMenu(OnVideoSpecialMenu mOnVideoSpecialMenu) {
		this.mOnVideoSpecialMenu = mOnVideoSpecialMenu;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mLstData.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return mLstData.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		Holder holder = null;
		if (convertView == null) {
			convertView = mLayoutInflater.inflate(R.layout.grid_waterfall_item,
					null);
			holder = new Holder();
			holder.layItem = (LinearLayout) convertView
					.findViewById(R.id.lay_item);
			holder.video_place = convertView.findViewById(R.id.video_place);
			holder.rl_uploadInfos = convertView
					.findViewById(R.id.rl_uploadInfos);
			holder.layuploadInfos = convertView
					.findViewById(R.id.lay_uploadInfos);
			holder.iv_cell_upload = (ImageView) convertView
					.findViewById(R.id.iv_cell_upload);
			holder.tv_second_title_upload = (TextView) convertView
					.findViewById(R.id.tv_second_title_upload);
			holder.image = (ImageView) convertView.findViewById(R.id.iv_image);
			holder.title = (TextView) convertView.findViewById(R.id.tv_title);
			holder.subtitle = (TextView) convertView
					.findViewById(R.id.tv_subtitle);
			holder.hot = (ImageView) convertView.findViewById(R.id.iv_hot);
			holder.frequency = (LinearLayout) convertView
					.findViewById(R.id.lay_frequency);
			holder.play = (TextView) convertView.findViewById(R.id.tv_play);
			holder.praise = (TextView) convertView.findViewById(R.id.tv_praise);
			convertView.setTag(holder);
		} else {
			holder = (Holder) convertView.getTag();
		}
		final VideoInfo info = mLstData.get(position);
		Logger.i(TAG, "mLstData.size==" + mLstData.size());
		final int index = position;
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, mHeight);
		LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		if (position % 2 == 0) {
			params.setMargins((int) margin, 0, 0, 0);
			param.setMargins((int) margin + (int) marginleft, (int) margin,
					(int) marginleft, (int)marginbottom);
		} else {
			params.setMargins(0, 0, (int) margin, 0);
			param.setMargins((int) marginleft, (int) margin, (int) margin
					+ (int) marginleft, (int)marginbottom);
		}
		holder.video_place.setLayoutParams(params);
		holder.layuploadInfos.setLayoutParams(params);
		if (mIsFreq == true) {
			if (!TextUtils.isEmpty(info.getState())
					&& "2".equals(info.getState())) {
				holder.title.setText("该视频审核未通过");
			} else {
				if (!TextUtils.isEmpty(info.getTitle())) {
					holder.title.setText(info.getTitle());
				} else {
					holder.title.setText("");
				}
			}
			holder.frequency.setLayoutParams(param);
			holder.frequency.setVisibility(View.VISIBLE);
			holder.subtitle.setVisibility(View.GONE);
			holder.play.setText("播放 " + Utility.getNum(info.getPlayNum()));
			holder.praise.setText("点赞 " +  Utility.getNum(info.getPraiseNum()+""));
		} else {
			holder.subtitle.setLayoutParams(param);
			if (!TextUtils.isEmpty(info.getRecommendTitle())) {
				holder.title.setText(info.getRecommendTitle());
			} else if (!TextUtils.isEmpty(info.getTitle())) {
				holder.title.setText(info.getTitle());
			} else {
				holder.title.setText("");
			}
			holder.frequency.setVisibility(View.GONE);
			holder.subtitle.setVisibility(View.VISIBLE);
			if (!TextUtils.isEmpty(info.getRecommendDetail())) {
				holder.subtitle.setText(info.getDetail());
			} else if (info.getUserInfo() != null
					&& (!TextUtils.isEmpty(info.getUserInfo().getNickname()) || !TextUtils
							.isEmpty(info.getUserInfo().getUserName()))) {
				if (!TextUtils.isEmpty(info.getUserInfo().getNickname())) {
					holder.subtitle.setText(info.getUserInfo().getNickname());
				} else if (!TextUtils.isEmpty(info.getUserInfo().getUserName())) {
					holder.subtitle.setText(info.getUserInfo().getUserName());
				}

				holder.subtitle.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (info != null
								&& info.getUserInfo() != null
								&& !TextUtils.isEmpty(info.getUserInfo()
										.getUserId())) {
							String userId = info.getUserInfo().getUserId();
							Intent intent = new Intent();
							if (LoginInfo.getInstance().isLogin()) {
								if (!TextUtils.isEmpty(userId)
										&& userId.equals(LoginInfo
												.getInstance().getUserId())) {
									if (info instanceof UploadInfo) {
										Logger.i(TAG,
												"videoInfo instanceof UploadInfo");
										return;
									}
									if (!TextUtils.isEmpty(info.state)
											&& info.state.equals("2")) {
										Logger.i(TAG,
												"videoInfo.state.equals 2");
										return;
									}
//									intent.setClass(mContext,
//											PersonalHomeActivity.class);
//									mContext.startActivity(intent);
								} else {
									intent.setClass(mContext,
											OtherPersonHomeActivity.class);
									intent.putExtra("userId", userId);
									mContext.startActivity(intent);
								}
							} else {
								intent.setClass(mContext,
										OtherPersonHomeActivity.class);
								intent.putExtra("userId", userId);
								mContext.startActivity(intent);
							}
						}
					}
				});
			} else {
				holder.subtitle.setText("");
			}
		}
		if (info.isTop()) {
			holder.hot.setVisibility(View.VISIBLE);
		} else {
			holder.hot.setVisibility(View.GONE);
		}
		android.view.ViewGroup.LayoutParams Params = holder.image
				.getLayoutParams();
		Params.width = LayoutParams.MATCH_PARENT; // 设置图片的宽度
		Params.height = mHeight;// 设置图片的高度
		holder.image.setLayoutParams(Params);
		holder.layItem.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (info != null && !TextUtils.isEmpty(info.getVideoId())) {
					Intent intent = new Intent();

					ScenarioVideoInfo video = new ScenarioVideoInfo(info
							.getVideoId() + "");
					if (video != null) {
						intent.setClass(mContext,
								PaikeVideoDetailActivity2.class);
						intent.putExtra("videoInfo", video);
						mContext.startActivity(intent);
					}
				}
			}
		});
		if (isMySelf == true) {
			holder.layItem.setOnLongClickListener(new OnLongClickListener() {

				@Override
				public boolean onLongClick(View v) {
					// TODO Auto-generated method stub
					if (mOnVideoSpecialMenu != null) {
						mOnVideoSpecialMenu.onVideoSpecialMenu(position, info);
					}
					return true;
				}
			});
		}
//		if (info instanceof UploadInfo && isMySelf) {
//			// holder.image.setImageResource(R.drawable.bendi_loading_bg);
//			// holder.title.setText("上传中，请耐心等待");
//
//			holder.frequency.setVisibility(View.GONE);
//			holder.rl_uploadInfos.setVisibility(View.VISIBLE);
//			holder.video_place.setVisibility(View.GONE);
//			final CircleProgressBar cicleBar = (CircleProgressBar) convertView
//					.findViewById(R.id.roundProgressBar);
//			ImageView btnPlay = (ImageView) convertView
//					.findViewById(R.id.center_upload_play);
//			holder.iv_cell_upload.setLayoutParams(Params);
//			holder.iv_cell_upload
//					.setImageResource(R.drawable.video9_16_loading);
//			if (UploadInfo.getInstance().getHerder() != null
//					&& ((UploadInfo) info).getHerder().sourceid
//							.equals(UploadInfo.getInstance().getHerder().sourceid)) {
//
//				cicleBar.setVisibility(View.VISIBLE);
//				((TextView) convertView.findViewById(R.id.tv_upload_percent))
//						.setText("上传中，请耐心等待");
//				btnPlay.setVisibility(View.GONE);
//				final Handler percentHandler = new Handler() {
//					@Override
//					public void handleMessage(Message msg) {
//						// TODO Auto-generated method stub
//						super.handleMessage(msg);
//						switch (msg.what) {
//						case 0:
//							cicleBar.setProgressNotInUiThread(msg.arg1);
//							break;
//						case 1:
//							((UploadInfo) info).getHerder().state = "1";
//							Header headerLod = ((UploadInfo) info).getHerder();
//							UploadInfo upInfo = new UploadInfo();
//							Header headerNew = new Header(headerLod);
//							upInfo.setHerder(headerNew);
//							UploadInfo.getInstance().clear();
//							mLstData.set(index, upInfo);
//							notifyDataSetChanged();
//							break;
//						}
//					}
//				};
//
//				new Thread() {
//
//					public void run() {
//
//						while (UploadInfo.getInstance().getPercent() < 100) {
//
//							try {
//								Thread.sleep(100);
//							} catch (InterruptedException e) {
//								// TODO Auto-generated catch block
//								e.printStackTrace();
//							}
//							Message msg = new Message();
//							msg.what = 0;
//							if (UploadInfo.getInstance().getPercent() != -1) {
//								msg.arg1 = UploadInfo.getInstance()
//										.getPercent();
//							} else {
//								msg.arg1 = 0;
//							}
//
//							percentHandler.sendMessage(msg);
//						}
//						Message msg1 = new Message();
//						msg1.what = 1;
//						percentHandler.sendMessage(msg1);
//					}
//
//				}.start();
//			} else if (((UploadInfo) info).getHerder().state.equals("0")) {
//				((TextView) convertView.findViewById(R.id.tv_upload_percent))
//						.setVisibility(View.VISIBLE);
//				((TextView) convertView.findViewById(R.id.tv_upload_percent))
//						.setText("网络异常，请点击续传");
//
//				btnPlay.setVisibility(View.VISIBLE);
//				cicleBar.setVisibility(View.GONE);
//				btnPlay.setOnClickListener(new OnClickListener() {
//
//					@Override
//					public void onClick(View arg0) {
//						// TODO Auto-generated method stub
//						Logger.i(TAG, "点击续传");
//						if (UploadInfo.getInstance().isUploading()) {
//							ToastAlone.showToast((Activity) mContext,
//									"您还有正在上传的视频，请稍后", 1);
//							return;
//						}
//						Header header = ((UploadInfo) info).getHerder();
//						header.related_Video_Id1 = header.related_Video_Id;
//						header.related_Video_Id = "";
//						header.scenario1 = header.scenario;
//						header.scenario = "";
//						UploadInfo.getInstance().startUpload(
//								((UploadInfo) info).getHerder().filePath,
//								header, mContext);
//						notifyDataSetChanged();
//					}
//				});
//			} else {
//				btnPlay.setVisibility(View.GONE);
//				cicleBar.setVisibility(View.GONE);
//				((TextView) convertView.findViewById(R.id.tv_upload_percent))
//						.setVisibility(View.VISIBLE);
//				((TextView) convertView.findViewById(R.id.tv_upload_percent))
//						.setText("转码中，请耐心等待");
//
//				// holder.image.setImageResource(R.drawable.video9_16_loading);
//			}
//			if (((UploadInfo) info).getHerder() != null) {
//				holder.tv_second_title_upload.setLayoutParams(param);
//				holder.tv_second_title_upload.setText(((UploadInfo) info)
//						.getHerder().title);
//			}
//			convertView.setOnClickListener(new OnClickListener() {
//
//				@Override
//				public void onClick(View v) {
//					Logger.i(TAG, "有点击convertView，但 不做操作");
//				}
//			});
//		} else {
			holder.rl_uploadInfos.setVisibility(View.GONE);
			holder.video_place.setVisibility(View.VISIBLE);
			if (TextUtils.isEmpty(info.getImgUrl())) {
				holder.image.setImageResource(R.drawable.video9_16_loading);
			} else {
				ImageLoader.getInstance().displayImage(info.getImgUrl(),
						holder.image, Constant.VIDEO_9_16_OPTION, null);
			}
//		}
		return convertView;
	}

	private class Holder {
		View video_place;
		View rl_uploadInfos;
		View layuploadInfos;
		TextView tv_second_title_upload;
		ImageView iv_cell_upload;
		public LinearLayout layItem;
		public ImageView image;
		public TextView title;
		public TextView subtitle;
		public LinearLayout frequency;
		public TextView play;
		public TextView praise;
		public ImageView hot;
	}
}
